﻿using System.Windows.Input;
using System.Windows;
namespace DeepEarth.Core
{
    public class WrapperCommand : DependencyObject, ICommand
    {
        public ICommand WrappedCommand
        {
            get { return (ICommand)GetValue(WrappedCommandProperty); }
            set { SetValue(WrappedCommandProperty, value); }
        }

        public static readonly DependencyProperty WrappedCommandProperty =
            DependencyProperty.Register("WrappedCommand", typeof(ICommand), typeof(WrapperCommand), new PropertyMetadata(WrappedCommandChanged));

        private static void WrappedCommandChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
        {
            // if we're wrapping a wrapper command, unwrap that wrapper command.
            if (args.NewValue != null)
            {
                WrapperCommand wc = args.NewValue as WrapperCommand;
                if (wc != null)
                {
                    WrapperCommand self = sender as WrapperCommand;
                    self.WrappedCommand = wc.WrappedCommand;
                }
            }
        }

        public bool CanExecute(object parameter)
        {
            if (WrappedCommand != null)
            {
                return WrappedCommand.CanExecute(parameter);
            }
            else
            {
                return false;
            }
        }

        public event System.EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            if (WrappedCommand != null)
            {
                WrappedCommand.Execute(parameter);
            }
        }
    }
}
